export const CHANNEL_NAME = 'hooks_storage'
const broadcastChannelMap = new Map()
const listenerMap = new Map()
//浏览器是否支持BroadcastChannel 若不支持则使用window.postMessage来通信
const isBroadcastChannelAvailable = ()=>{
  try{
    const bc = new BroadcastChannel(CHANNEL_NAME);
    return true
  }catch (e) {
    return false
  }
}
//发送事件
export const emit = (key,value)=>{
  if(isBroadcastChannelAvailable()){
    const bc = new BroadcastChannel(CHANNEL_NAME);
    bc.postMessage({key,value})
  }else{
    console.log('postMessage')
    window.postMessage({key,value},"*")
  }

}
//监听事件并回调
export const monitor = (key,callback)=>{
  const listener = (event)=>{
    //console.log('receiverMsg')
    callback(event.data)
  }
  if(isBroadcastChannelAvailable()){
    const  broadcastChannel = new BroadcastChannel(CHANNEL_NAME);
    broadcastChannel.addEventListener('message',listener)
    broadcastChannelMap.set(key,broadcastChannel)
  }else{
    //可返回对创建该窗口的 Window 对象的引用。
    window.opener && window.opener.addEventListener('message',listener)
  }
  listenerMap.set(key,listener)
}
//移除事件监听
export const clearMonitor = (key)=>{
  if(listenerMap.has(key)){
    if(isBroadcastChannelAvailable()){
      broadcastChannelMap.get(key).removeEventListener('message',listenerMap.get(key))
      broadcastChannelMap.get(key).close()
      broadcastChannelMap.delete(key)
    }else{
      window.removeEventListener('message',listenerMap.get(key))
    }
    listenerMap.delete(key)
  }
}
